class ChecklistController < ApplicationController
  def index
    @tags = Checklist.tag_counts
  end

#  def tag_cloud
#    @tags = Checklist.tag_counts
#  end

  def new
    @checklist = Checklist.new(params[:checklist])
    @checklist.items.build(params[:items])
    @items = @checklist.items
  end

  def edit
    @checklist = Checklist.find(:first, :conditions => {:id=>params[:id]})
    @items = @checklist.items
    render :action => "edit"
  end

  def save
    @checklist = Checklist.new(params[:checklist])
    @checklist.items.build(params[:items])
    @items = @checklist.items
    validate_and_save
  end

  def update
    @checklist = Checklist.find(:first, :conditions=>{:name=>params[:checklist][:name]})
    @checklist.items=[];
    @checklist.items.build(params[:items])
    @items = @checklist.items
    @checklist.tag_list = params[:checklist][:tag_list]
    validate_and_save
  end

  def search
    @search_query=params[:search_query]
    @checklists = Checklist.find_with_sphinx @search_query
    render :template => "checklist/list"
  end

  def tag
    @tag = params[:tag_name]
    @checklists = Checklist.find_tagged_with(@tag)
    render :template => "checklist/list"
  end

  def list
    @checklists = Checklist.find(:all)
  end

  def validate_and_save
    if @checklist.valid?
      @checklist.save!
      redirect_to :action => "index"
      return
    else
      puts "\n Errors : " + @checklist.errors.inspect + "\n"
      render :action => "new"
    end
  end
  private :validate_and_save

  def show
    @checklist=Checklist.find(:first, :conditions => { :id => params[:id]})
  end
end
